<template>
  <div id="networkAnalysis">
    <search-poi @child-event="findPathByInput" v-if="isShowSearchpoi">
    </search-poi>
    <path-plan-results
      :path="pathobj"
      v-if="pathlist.length"
      ref="PathPlanResults"
    />
  </div>
</template>

<script>
import L from "leaflet";

import {
  TransportationAnalystResultSetting,
  TransportationAnalystParameter,
  FindPathParameters,
  networkAnalystService,
} from "@supermap/iclient-leaflet";

import PathPlanResults from "./PathPlanResults.vue";
import SearchPoi from "./SearchPoi.vue";
export default {
  components: { PathPlanResults, SearchPoi },
  data() {
    return {
      pointnumber: 0,
      startname: undefined,
      endname: undefined,
      text: ``,
      pathlist: [],
      isSearchpoi: false,
    };
  },
  props: ["isShowSearchpoi"],
  computed: {
    map() {
      return this.$store.state.map;
    },
    NetworkLayer() {
      return this.$store.state.config.NetworkLayer;
    },
    routeGroup() {
      return this.$store.state.routeGroup;
    },
  },
  methods: {
    dealstringnum(string) {
      let arr = string.match(/\d+(.\d+)?/g);
      // console.log(arr);
      let arr1 = string.split(arr[0]);
      return arr1[0] + arr[0];
    },
    againaddSEMarker() {
      this.startMarker.addTo(this.routeGroup);
      this.endMarker.addTo(this.routeGroup);
    },
    addrightMenu() {
      L.setOptions(this.map, {
        contextmenu: true,
        contextmenuWidth: 100,
        contextmenuItems: [
          {
            text: "设为起点",
            icon: "./img/icons/icon_搜索_起点.svg",
            callback: this.buildStartPoint,
          },
          {
            text: "设为终点",
            icon: "./img/icons/icon_搜索_终点.svg",
            callback: this.buildEndPoint,
          },
        ],
      });
      window.handler = new L.Map.ContextMenu(this.map).enable();
    },
    buildStartPoint: function (e) {
      this.startname = undefined;
      this.endname = undefined;
      if (this.startpoint) {
        return;
      }
      if (this.pointnumber == 0) {
        this.startMarker = undefined;
        this.endMarker = undefined;
        this.$parent.isShowSearchpoi = false;
        this.routeGroup.clearLayers();
      }

      this.startpoint = L.point(e.latlng.lng, e.latlng.lat);
      let latlng = [e.latlng.lat, e.latlng.lng];
      let icon = L.icon({
        iconSize: [25, 40],
        iconAnchor: [13, 40],
        iconUrl: `./img/icons/icon_搜索_起点.svg`,
      });
      this.startMarker = L.marker(latlng, {
        icon: icon,
        draggable: true,
      }).addTo(this.routeGroup);
      let self = this;
      this.startMarker.on("dragend", () => {
        self.pointdragfun();
      });
      this.pointnumber = this.pointnumber + 1;
      if (this.pointnumber == 2) {
        this.findpath();
      }
    },
    buildEndPoint: function (e) {
      this.startname = undefined;
      this.endname = undefined;
      if (this.endpoint) {
        return;
      }
      if (this.pointnumber == 0) {
        this.startMarker = undefined;
        this.endMarker = undefined;
        this.$parent.isShowSearchpoi = false;
        this.routeGroup.clearLayers();
      }

      this.endpoint = L.point(e.latlng.lng, e.latlng.lat);
      let latlng = [e.latlng.lat, e.latlng.lng];
      let icon = L.icon({
        iconSize: [25, 40],
        iconAnchor: [13, 40],
        iconUrl: `./img/icons/icon_搜索_终点.svg`,
      });
      this.endMarker = L.marker(latlng, {
        icon: icon,
        draggable: true,
      }).addTo(this.routeGroup);
      //拖动
      let self = this;
      this.endMarker.on("dragend", () => {
        self.pointdragfun();
      });
      this.pointnumber = this.pointnumber + 1;
      if (this.pointnumber == 2) {
        this.findpath();
      }
    },
    pointdragfun() {
      if (this.startMarker)
        this.startpoint = L.point(
          this.startMarker._latlng.lng,
          this.startMarker._latlng.lat
        );
      if (this.endMarker)
        this.endpoint = L.point(
          this.endMarker._latlng.lng,
          this.endMarker._latlng.lat
        );
      this.timeout = 0;
      let self = this;
      setTimeout(function () {
        self.timeout++;
      }, 500);
      setTimeout(function () {
        if (self.timeout && self.startMarker && self.endMarker) {
          self.routeGroup.clearLayers();
          self.againaddSEMarker();
          self.findpath();
        }
      }, 1000);
    },
    findPathParam: function (startpoint, endpoint) {
      //创建最佳路径分析参数实例
      let resultSetting = new TransportationAnalystResultSetting({
        returnEdgeFeatures: true,
        returnEdgeGeometry: true,
        returnEdgeIDs: true,
        returnNodeFeatures: true,
        returnNodeGeometry: true,
        returnNodeIDs: true,
        returnPathGuides: true,
        returnRoutes: true,
      });
      let analystParameter = new TransportationAnalystParameter({
        resultSetting: resultSetting,
        weightFieldName: "SmLength",
      });
      let findPathParameter = new FindPathParameters({
        isAnalyzeById: false,
        nodes: [startpoint, endpoint],

        hasLeastEdgeCount: false,
        parameter: analystParameter,
      });
      return findPathParameter;
    },
    findpath() {
      this.pointnumber = 0;
      var serviceUrl = window.getServiceUrl(
        this.NetworkLayer.url,
        window.servicesPorts.iserver
      );
      //创建最佳路径分析服务实例
      let findPathService = networkAnalystService(serviceUrl);
      let findPathParameter = this.findPathParam(
        this.startpoint,
        this.endpoint
      );

      this.endpoint = undefined;
      this.startpoint = undefined;
      //进行查找
      let self = this;
      this.pathlist = [];
      findPathService.findPath(findPathParameter, function (serviceResult) {
        let result = serviceResult.result;

        if (!result) {
          self.$message.info("路径规划失败，请检查路径网络服务");
          return;
        }
        let i = 0;
        result.pathList.map((item) => {
          self.pathlist.push({
            id: i,
            route: item.route,
            pathGuideItems: item.pathGuideItems,
          });
          i++;
        });
        self.pathobj = {
          pathlist: self.pathlist,
          start: {
            startname: self.startname,
            startpoint: self.startpoint,
          },
          end: {
            endname: self.endname,
            endpoint: self.endpoint,
          },
        };
        // self.currentRouteGuide = self.pathlist[0].pathGuideItems.features;
        // self.routelinecoordinates = self.pathlist[0].route.geometry.coordinates;
        // self.$refs.PathPlanResults.route2map(self.routelinecoordinates);
        // console.log("路径方案", self.pathlist);
      });
    },
    findPathByInput(point) {
      // console.log(point);
      this.startpoint = point.startpoint;
      this.endpoint = point.endpoint;
      this.startname = point.startname;
      this.endname = point.endname;
      this.findpath();
    },
  },
  mounted() {
    this.addrightMenu();
  },
};
</script>

<style lang="less">
#networkAnalysis {
  .search-sepoi {
    // position: absolute;
    // top: 40px;
    // left: 30px;

    max-width: 800px;
  }
}
</style>
